package 剑指offer;

import java.util.HashMap;

/**
 * @description:
 * @author: ywk
 * @date: 2021-03-13
 */
public class 前缀 {
    //1.通过HashMap存储
    static int subArraySum(int[] nums, int k) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        int ans = 0, sum = 0;
        map.put(0, 1);
        for (int i = 0; i < n; i++) {
            sum += nums[i];
            int sumPre = sum - k;
            ans += map.getOrDefault(sumPre, 0);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return ans;
    }

    //2.通过前缀表
    static int subArraySumArr(int[] nums, int k) {
        int n = nums.length;
        int[] sum = new int[n + 1];
        sum[0] = 0;
        for (int i = 0; i < n; i++) {
            sum[i + 1] = sum[i] + nums[i];
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (sum[i] - sum[j] == k) {
                    ans++;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(subArraySumArr(new int[]{1, 2, 2, 4, 3}, 8));
    }
}